﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media;
using Aribaccio;
using Aribaccio.Copyright;
using Aribaccio.Logger;
using BDPAutodetect.Mgrcore;
using BDPAutodetect.Models;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;

namespace BDPAutodetect.Client
{
    /// <summary>
    /// 登录窗体视图模型类
    /// </summary>
    public partial class LoginWindowModel : BaseViewModel<Window>
    {
        /// <summary>
        /// 损失费
        /// </summary>
        protected bool IsLogining { get; set; }
        /// <summary>
        /// 构造器管理辅助
        /// </summary>
        protected AppLoader Loader { get; set; }
        /// <summary>
        /// 主窗体
        /// </summary>
        protected MainWindow MainWin { get; set; }
        /// <summary>
        /// 用户管理辅助
        /// </summary>
        protected UserManager UserMgr { get; set; }
        /// <summary>
        /// 系统参数管理实例
        /// </summary>
        protected SettingSystemManager SettingSystemMgr { get; set; }

        /// <summary>
        /// 显示登录信息
        /// </summary>
        [ObservableProperty]
        protected MLoginDto loginItem;
        /// <summary>
        /// 登录信息
        /// </summary>
        [ObservableProperty]
        protected string loginMsg;
        /// <summary>
        /// 版权期限启用状态
        /// </summary>
        [ObservableProperty]
        protected bool enableCopyLimits = true;
        /// <summary>
        /// 期限天数
        /// </summary>
        [ObservableProperty]
        [NotifyPropertyChangedFor(nameof(LimitSurplusDaysDisplay))]
        protected IRegisterCopyMsg? registerCopyright;
        /// <summary>
        /// 期限天数画刷颜色
        /// </summary>
        [ObservableProperty]
        protected Brush limitSurplusDaysForeground = new SolidColorBrush(Colors.Red);
        /// <summary>
        /// 期限天数显示文本
        /// </summary>
        public string LimitSurplusDaysDisplay => this.RegisterCopyright?.LimitSurplusDaysDisplay ?? "试用天数：0";

        /// <summary>
        /// 默认构造函数
        /// </summary>
        public LoginWindowModel(MainWindow argMainWindow, AppLoader argLoader, UserManager argUserManager, SettingSystemManager argSystemManager)
        {
            this.MainWin = argMainWindow;
            this.Loader = argLoader;
            this.UserMgr = argUserManager;
            this.SettingSystemMgr = argSystemManager;
            this.LoginMsg = string.Empty;
            this.LoginItem = new MLoginDto() { UserName = "admin", UserPassword = "admin" };
            this.Loader.ResultEvent += ShowMsg;
        }

        /// <summary>
        /// 窗体初始化加载事件
        /// </summary>
        [RelayCommand]
        protected void ExecuteLoaded()
        {
            //先用户记忆功能，用户信息存XML文件
            //再检查系统数据库初始化连接状态
            if (!this.SettingSystemMgr.IsValid)
            {
                this.LoginMsg = "系统初始化连接异常";
                return;
            }
            //获取系统参数, 版权期限启用状态
            this.EnableCopyLimits = this.SettingSystemMgr.GetSettingTypeData<bool>(SettingType.EnableCopyLimits, true);
            if (this.EnableCopyLimits)
            {
                //初始化检查注册序列号及期限
                this.RegisterCopyright = this.Loader.GetCopyrightLimits();
                if (this.RegisterCopyright == null) return;
                if (this.RegisterCopyright.Status != RegisterCopyStatus.OK && this.RegisterCopyright.Status != RegisterCopyStatus.OKTimeLimits)
                {
                    this.LoginMsg = $"{this.RegisterCopyright.StatusMsg}, 请联系技术支持";
                }
                else
                {
                    if (this.RegisterCopyright.LimitSurplusDays <= 7)
                    {
                        this.LimitSurplusDaysForeground = new SolidColorBrush(Colors.Red);
                    }
                    else if (this.RegisterCopyright.LimitSurplusDays > 7 && this.RegisterCopyright.LimitSurplusDays <= 15)
                    {
                        this.LimitSurplusDaysForeground = new SolidColorBrush(Colors.Yellow);
                    }
                    else
                    {
                        this.LimitSurplusDaysForeground = new SolidColorBrush(Colors.White);
                    }
                }
            }          
        }

        /// <summary>
        /// 窗体最小化操作事件
        /// </summary>
        [RelayCommand]
        protected void ExecuteWindowMin()
        {
            if (this.Parent == null) return;
            this.Parent.WindowState = WindowState.Minimized;
        }

        /// <summary>
        /// 窗体最大化操作事件
        /// </summary>
        [RelayCommand]
        protected void ExecuteWindowMax()
        {
            if (this.Parent == null) return;
            this.Parent.WindowState = this.Parent.WindowState == WindowState.Maximized
                ? WindowState.Normal
                : WindowState.Maximized;
        }

        /// <summary>
        /// 窗体关闭操作事件
        /// </summary>
        [RelayCommand]
        protected void ExecuteWindowClose()
        {
            if (this.Parent == null) return;
            this.Parent.Close();
            Application.Current.Shutdown();
        }

        /// <summary>
        /// 窗体拖拽操作事件
        /// </summary>
        [RelayCommand]
        protected void ExecuteDragMove()
        {
            if (this.Parent == null) return;
            this.Parent.DragMove();
        }

        /// <summary>
        /// 用户登录事件
        /// </summary>
        [RelayCommand]
        protected async Task ExecuteLogin()
        {
            this.LoginMsg = string.Empty;
            if (!this.CheckPre()) return;

            this.IsExecutedIdle = false;
            //用户登录验证
            this.LoginMsg = "登录中，请等待...";
            Result resultLogin = await this.UserMgr.UserLogin(this.LoginItem);
            if (!resultLogin.ResultState)
            {
                this.IsExecutedIdle = true;
                this.ShowMsg($"登录失败, {resultLogin.ResultMsg}");
                return;
            }
            //构造初始化
            var result = this.Loader.InitializeService();
            await result.ConfigureAwait(false);
            this.IsExecutedIdle = true;
            //登录主页面，关闭当前登录界面
            await Task.Factory.StartNew(() =>
            {
                this.Parent?.Close();
                this.MainWin.Show();
            }, new CancellationTokenSource().Token, TaskCreationOptions.None, base.syncContextTask);
        }

        /// <summary>
        /// 登录前检查
        /// </summary>
        /// <returns></returns>
        protected bool CheckPre()
        {
            if (!this.IsExecutedIdle) return false;
            if (!this.SettingSystemMgr.IsValid)
            {
                this.LoginMsg = "系统初始化连接异常";
                return false;
            }
            if (this.EnableCopyLimits)
            {
                if (this.RegisterCopyright == null) return false;
                if (this.RegisterCopyright.LimitSurplusDays <= 0) return false;
            }
            if (string.IsNullOrWhiteSpace(this.LoginItem.UserName))
            {
                this.LoginMsg = "请输入用户名!";
                return false;
            }
            if (string.IsNullOrWhiteSpace(this.LoginItem.UserPassword))
            {
                this.LoginMsg = "请输入密码!";
                return false;
            }
            return true;
        }

        /// <summary>
        /// 显示信息
        /// </summary>
        /// <param name="argResultMsg"></param>
        protected void ShowMsg(string argResultMsg)
        {
            this.LoginMsg = argResultMsg;
            LoggerMgrcore.Instance.WriteInfo(this.LoginMsg);
        }
    }
}
